﻿using System;
using Nuwanda.Common;
using System.Diagnostics;

namespace Nuwanda.TfsSpotlight.Data
{
    /// <summary>Describes a TFS query</summary>
    [Author("Bartłomiej Legiędź")]
    public class QueryDescriptor
    {
        private const string SEARCH_QUERY =
            @"SELECT [System.Id], [System.Title], [Microsoft.VSTS.Common.ActivatedBy], [System.WorkItemType] FROM WorkItems WHERE [System.TeamProject] = @project  AND [System.Title] CONTAINS '{0}' ORDER BY [System.Id], [System.WorkItemType]";

        /// <summary>Query name</summary>
        public string Name { [DebuggerStepThrough] get; private set; }

        /// <summary>A unique guid</summary>
        public Guid Guid { [DebuggerStepThrough] get; private set; }

        /// <summary>Query text (WIQL)</summary>
        public string Text { [DebuggerStepThrough] get; private set; }

        /// <summary>Whether the query is private or not</summary>
        public bool IsPrivate { [DebuggerStepThrough] get; private set; }

        /// <summary>A project that the query belongs to</summary>
        public ProjectDescriptor Project { [DebuggerStepThrough] get; private set; }

        public QueryDescriptor(string name, Guid guid, string text, bool isPrivate, ProjectDescriptor project)
        {
            this.Name = name;
            this.Guid = guid;
            this.Text = text;
            this.IsPrivate = isPrivate;
            this.Project = project;
        }

        /// <summary>Returns a query used for searching <paramref name="searchText"/> in titles of work items from <paramref name="project"/></summary>
        /// <param name="searchText">Text to search</param>
        /// <param name="project">Project to search within</param>
        /// <returns>Query</returns>
        public static QueryDescriptor GetSearchQuery(string searchText, ProjectDescriptor project)
        {
            if (project == null)
                throw new ArgumentNullException("project");

            return new QueryDescriptor(String.Format(Captions.SearchQueryName, searchText, project.Name), Guid.NewGuid(),
                String.Format(SEARCH_QUERY, searchText), false, project);
        }

        public string GetChartConfigurationFileName()
        {
            return String.Format("QueryChart.{0}.chart", this.Guid);
        }
    }
}
